package com.hydra.base.utils;

import com.hydra.base.error.ValidateException;
import lombok.val;
import org.apache.http.util.TextUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 校验工具
 * @Author Hydra
 * @Date 2022/6/2 23:31
 */
public class ValidateUtil {

    public static void validateNotEmpty(String value, String name){
        validateNotEmpty(value, name, null);
    }

    public static void validateNotEmpty(String value, String name, String error){
        if(TextUtils.isEmpty(value)){
            String message = error;
            if(TextUtils.isEmpty(message)){
                message = "请输入"+name+"！";
            }
            throw new ValidateException(message);
        }
    }

    public static void validateEmail(String value, String name, boolean empty){
        if(!empty){
            validateNotEmpty(value, name);
        }
        if(!TextUtils.isEmpty(value)){
            if(value.length() > 100){
                throw new ValidateException("邮箱长度过长！请检查后重试");
            }

            String regex = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
            match(value, name, regex);
        }
    }

    public static void validatePhone(String value, String name, boolean empty){
        if(!empty){
            validateNotEmpty(value, name);
        }
        if(!TextUtils.isEmpty(value)){
            String regex = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$";
            match(value, name, regex);
        }
    }

    public static void validatePassword(String value, String name, boolean empty){
        if(!empty){
            validateNotEmpty(value, name);
        }
        if(!TextUtils.isEmpty(value)){
            String regex = "^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[\\(\\)])+$)([^(0-9a-zA-Z)]|[\\(\\)]|[a-z]|[A-Z]|[0-9]){6,20}$";
            match(value, name, regex, "请输入包含大小写字母/数字/符号任意两者组合的6-20位密码！");
        }
    }

    private static void match(String value, String name, String regex){
        match(value, name, regex, null);
    }

    private static void match(String value, String name, String regex, String error){
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(value);
        if(!matcher.matches()){
            String message = error;
            if(TextUtils.isEmpty(message)){
                message = name+"格式错误！";
            }
            throw new ValidateException(message);
        }
    }

}
